package com.zjp.plugins;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Statement;

@Intercepts({
        // 签名数组 拦截不同的接口和方法
        @Signature(
                // 设置拦截的接口
                type = StatementHandler.class,
                // 设置拦截的方法（需要和接口匹配）
                method = "query",
                // 设置拦截方法的参数类型数组，通过方法名和参数类型可以确定一个方法
                args = {
                        Statement.class, ResultHandler.class
                }
        )
})
public class SQLInterceptor implements Interceptor {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();
        log.info("==SQL== {}", sql);
        try {
            return invocation.proceed();
        } finally {
            log.info("==SQL 耗时== {}ms", (System.currentTimeMillis() - startTime));
        }
    }


}
